import numpy as np
import matplotlib.pyplot as plt

from sklearn.datasets import make_multilabel_classification
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC
from sklearn.decomposition import PCA

def plot_hyperplane(clf,min_x,max_x,line_style,label):
    # 画图
    w=clf.coef_[0]
    a=-1*w[0]/w[1]
    xx=np.linspace(min_x-5,max_x+5)
    yy=a*xx-(clf.intercept_[0])/w[1]
    plt.plot(xx,yy,line_style,label=label)

def plot_subfigure(X,Y,subplot,title):
    # 将X进行降维操作，变成两维的数据
    X=PCA(n_components=2).fit_transform(X)
    min_x=np.min(X[:,0])
    max_x=np.max(X[:,0])

    min_y=np.min(X[:,1])
    max_y=np.max(X[:,1])

    classif=OneVsRestClassifier(SVC(kernel='linear'))
    classif.fit(X,Y)

    plt.subplot(2,2,subplot)
    plt.title(title)

    zero_class=np.where(Y[:,0])
    #one_class=np.where(Y[:,1])
    plt.scatter(X[:,0],X[:,1],s=40,c='gray')
    plt.scatter(X[zero_class,0],X[zero_class,1],s=160,edgecolors='b',facecolors='none',
                linewidths=2,label='Class 1')
    plt.scatter(X[zero_class,0],X[zero_class,1],s=80,edgecolors='orange',facecolors='none',
                linewidths=2,label='Class 2')

    plot_hyperplane(classif.estimators_[0],min_x,max_x,'r--','Boundary\nfor class 1')
    plot_hyperplane(classif.estimators_[1],min_x,max_x,'k-.','Boundary\nfor class 2')

    plt.xticks(())
    plt.yticks(())

    plt.xlim(min_x-.5*max_x,max_x+.5*max_x)
    plt.ylim(min_y-.5*max_y,max_y+.5*max_y)

    if subplot==1:
        plt.xlabel('First principal component')
        plt.ylabel('Second principal component')
        plt.legend(loc='upper left')

def main():
    plt.figure(figsize=(8,6))
    X,Y=make_multilabel_classification(n_classes=2,n_labels=1,
                                       allow_unlabeled=False,# 该参数控制是否有类别缺省的数据，False表示没有
                                       random_state=1)

    plot_subfigure(X,Y,1,'With unlabeled samples + CCA')
    plt.subplots_adjust(.04,.02,.97,.94,.09,.2)
    plt.show()


main()